<template>
  <div class="search-panel">
    <t-row justify="space-between" align="middle">
      <!-- 左侧操作区域 -->
      <div class="left-operation-container">
        <t-space>
        <template v-for="button in buttons" :key="button.name">
          <!-- 确认类型的按钮使用 t-popconfirm -->
          <t-popconfirm
            v-if="button.confirm"
            :content="button.confirmMessage || `确定要执行${button.label}操作吗？`"
            @confirm="() => emitButtonClick(button)"
            theme="warning"
            :show-arrow="true"
          >
            <t-button
              :theme="button.theme || 'default'"
              :variant="button.variant || 'base'"
              :disabled="getButtonDisabled(button)"
            >
              <template #icon v-if="button.icon">
                <t-icon :name="button.icon" />
              </template>
              {{ button.label }}
            </t-button>
          </t-popconfirm>
          
          <!-- 普通按钮 -->
          <t-button
            v-else
            :theme="button.theme || 'default'"
            :variant="button.variant || 'base'"
            :disabled="getButtonDisabled(button)"
            @click="emitButtonClick(button)"
          >
            <template #icon v-if="button.icon">
              <t-icon :name="button.icon" />
            </template>
            {{ button.label }}
          </t-button>
        </template>
          <p v-if="!!selectedRowKeys?.length" class="selected-count">
            已选择 {{ selectedRowKeys.length }} 项
          </p>
        </t-space>
      </div>

      <!-- 右侧查询区域 -->
      <div class="search-basic">
        <t-space>
          <t-input 
            v-model="keyword" 
            :placeholder="basicPlaceholder" 
            clearable 
            @enter="handleSearch"
          >
            <template #suffix-icon>
              <t-icon name="search"/>
            </template>
          </t-input>
          <t-button @click="handleSearch">
            <template #icon><t-icon name="search" /></template>
            查询
          </t-button>
          <t-button @click="showAdvanced = true" v-if="hasAdvanced && advancedFields.length > 0">
            <template #icon><t-icon name="filter" /></template>
            高级查询
          </t-button>
          <t-button @click="handleReset" v-if="showReset">
            <template #icon><t-icon name="refresh" /></template>
            重置
          </t-button>
        </t-space>
      </div>
    </t-row>

    <!-- 高级查询弹窗 -->
    <t-dialog
      v-model:visible="showAdvanced"
      :header="advancedTitle"
      :width="dialogWidth"
      :on-confirm="handleAdvancedSearch"
      :on-close="handleAdvancedClose"
    >
      <t-form 
        :data="advancedData" 
        :label-width="formLabelWidth" 
        :layout="formLayout"
        ref="advancedFormRef"
      >
        <t-row :gutter="[0, 16]">
          <t-col 
            v-for="field in advancedFields" 
            :key="field.name"
            :span="field.span || 12"
          >
            <t-form-item 
              :label="field.label"
              :name="field.name"
            >
              <component
                :is="getFieldComponent(field.type)"
                v-model="advancedData[field.name]"
                :placeholder="field.placeholder || `请输入${field.label}`"
                :clearable="field.clearable !== false"
                :options="field.options"
                :range="field.range || (field.type === 'date-range' ? ['开始时间', '结束时间'] : undefined)"
                :multiple="field.multiple"
                :format="field.format"
                :value-format="field.valueFormat"
                :disabled="field.disabled"
              />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
      
      <!-- 底部操作按钮 -->
      <template #footer>
        <t-space>
          <t-button @click="handleAdvancedReset">重置</t-button>
          <t-button theme="primary" @click="handleAdvancedSearch">确定</t-button>
          <t-button theme="default" variant="outline" @click="handleAdvancedClose">取消</t-button>
        </t-space>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

// 按钮配置定义
interface ButtonConfig {
  name: string
  label: string
  theme?: 'default' | 'primary' | 'danger' | 'warning' | 'success'
  variant?: 'base' | 'outline' | 'dashed' | 'text'
  icon?: string
  disabled?: boolean
  requireSelection?: boolean
  confirm?: boolean
  confirmMessage?: string
  confirmTitle?: string
}

// 字段类型定义
interface SearchField {
  name: string
  label: string
  type: 'input' | 'select' | 'date' | 'date-range' | 'number' | 'textarea'
  placeholder?: string | string[]
  clearable?: boolean
  options?: Array<{ label: string; value: any }>
  span?: number
  multiple?: boolean
  format?: string
  valueFormat?: string
  range?: string[]
  disabled?: boolean
}

// Props
interface Props {
  // 按钮配置
  buttons?: ButtonConfig[]
  selectedRowKeys?: any[]
  
  // 基础查询
  keyword?: string
  basicPlaceholder?: string
  showReset?: boolean
  
  // 高级查询
  hasAdvanced?: boolean
  advancedTitle?: string
  advancedFields?: SearchField[]
  dialogWidth?: string
  formLabelWidth?: string | number
  formLayout?: 'vertical' | 'inline'
  
  // 响应式布局
  responsive?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  buttons: () => [],
  selectedRowKeys: () => [],
  basicPlaceholder: '请输入关键字',
  showReset: true,
  hasAdvanced: true,
  advancedTitle: '高级查询',
  advancedFields: () => [],
  dialogWidth: '600px',
  formLabelWidth: '80px',
  formLayout: 'vertical',
  responsive: true
})

// Emits
const emit = defineEmits<{
  search: [keyword: string]
  advancedSearch: [data: Record<string, any>]
  reset: []
  'update:keyword': [keyword: string]
  buttonClick: [buttonName: string, data?: any]
}>()

// 响应式数据
const keyword = ref(props.keyword || '')
const showAdvanced = ref(false)
const advancedData = ref<Record<string, any>>({})
const advancedFormRef = ref()

// 监听keyword变化
watch(keyword, (newValue) => {
  emit('update:keyword', newValue)
})

// 初始化高级查询字段
const initAdvancedData = () => {
  advancedData.value = {}
  props.advancedFields.forEach(field => {
    // 根据字段类型设置初始值
    switch (field.type) {
      case 'date-range':
        advancedData.value[field.name] = []
        break
      case 'select':
        if (field.multiple) {
          advancedData.value[field.name] = []
        } else {
          advancedData.value[field.name] = ''
        }
        break
      default:
        advancedData.value[field.name] = ''
    }
  })
}

// 初始化数据
initAdvancedData()

// 方法
const handleSearch = () => {
  emit('search', keyword.value)
}

const handleReset = () => {
  keyword.value = ''
  initAdvancedData()
  emit('reset')
  emit('search', '')
}

const handleAdvancedSearch = () => {
  console.log('SearchPanel: 高级查询数据:', advancedData.value)
  showAdvanced.value = false
  emit('advancedSearch', { ...advancedData.value })
}

const handleAdvancedReset = () => {
  initAdvancedData()
  if (advancedFormRef.value) {
    advancedFormRef.value.reset()
  }
}

const handleAdvancedClose = () => {
  showAdvanced.value = false
}

const getFieldComponent = (type: string) => {
  const components = {
    input: 't-input',
    select: 't-select',
    date: 't-date-picker',
    'date-range': 't-date-range-picker',
    number: 't-input-number',
    textarea: 't-textarea'
  }
  return components[type as keyof typeof components] || 't-input'
}

// 按钮处理方法
const getButtonDisabled = (button: ButtonConfig) => {
  // 如果按钮本身配置了禁用状态
  if (button.disabled) return true
  
  // 如果按钮需要选中项，但当前没有选中项
  if (button.requireSelection && (!props.selectedRowKeys || props.selectedRowKeys.length === 0)) {
    return true
  }
  
  return false
}

// 发射按钮点击事件
const emitButtonClick = (button: ButtonConfig) => {
  emit('buttonClick', button.name, {
    selectedRowKeys: props.selectedRowKeys,
    keyword: keyword.value
  })
}

// 暴露方法给父组件
defineExpose({
  reset: handleReset,
  showAdvanced: () => showAdvanced.value = true,
  setAdvancedData: (data: Record<string, any>) => {
    Object.assign(advancedData.value, data)
  }
})
</script>

<style lang="less" scoped>
.search-panel {
  // margin-bottom: var(--td-comp-margin-l);
  .left-operation-container {
    display: flex;
    align-items: center;
    
    .selected-count {
      margin-left: var(--td-comp-margin-l);
      color: var(--td-text-color-secondary);
    }
  }
  
  .search-basic {
    display: flex;
    justify-content: flex-end;
  }
}
</style>